import { PlusOutlined, SketchOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Popconfirm, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryRule, updateRule, addRule, removeRule, putDefault } from './service';
import styles from '../../../../global.less';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handleDefault = async (payload, actionRef) => {
  const hide = message.loading('正在设置');
  if (!payload) return true;
  try {
    await putDefault(payload);
    hide();
    message.success('设置成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('设置失败，请重试');
    return false;
  }
};
const { Option } = Select;
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [count, setCount] = useState();
  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '规则名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '增送周期类型',
      dataIndex: 'periodType',
      valueEnum: {
        1: {
          text: '永久',
        },
        2: {
          text: '年',
        },
        3: {
          text: '月',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择周期类型">
            <Option value={1}>永久</Option>
            <Option value={2}>年</Option>
            <Option value={3}>月</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '增送周期类型为必选项',
          },
        ],
      },
    },
    {
      title: '增送周期',
      dataIndex: 'period',
    },
    {
      title: '是否为默认规则',
      dataIndex: 'isDefault',
      valueEnum: {
        true: {
          text: '是',
          status: 'Success',
        },
        false: {
          text: '否',
          status: 'Default',
        },
      },
    },
    {
      title: '积分增送比例',
      dataIndex: 'scale',
      render: (_, record) => {
        return <span>{_ + '%'}</span>;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '积分增送比例为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: '消费',
          status: 'Processing',
        },
        2: {
          text: '充值',
          status: 'Success',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择类型">
            <Option value={1}>消费</Option>
            <Option value={2}>充值</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '状态为必选项',
          },
        ],
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                handleUpdateModalVisible(true);
                const list = JSON.parse(JSON.stringify(record));
                // list.scale = list.scale * 100;
                setStepFormValues(list);
                handleModalVisible(true);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleDefault(record.id, actionRef);
              }}
            >
              设置默认规则
            </a>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="规则列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleUpdateModalVisible(false);
              setStepFormValues();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total)
          return list;
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />

      <CreateForm
        title={updateModalVisible ? '修改规则' : '新建规则'}
        width={1000}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            if (value.scale && Number(value.scale) > 0) {
              // value.scale = Number(value.scale) * 0.01;
              updateModalVisible ? (value.id = stepFormValues.id) : null;
              const success = updateModalVisible
                ? await handleUpdate(value)
                : await handleAdd(value);
              if (success) {
                handleModalVisible(false);

                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            } else {
              message.error('积分赠送比例必须大于0!');
            }
          }}
          rowKey="id"
          bordered
          form={{
            initialValues: updateModalVisible === true ? stepFormValues : '',
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 6 },
            wrapperCol: { span: 20 },
          }}
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
